/**
 * Copyright (c) 2018-2022, NXOS Development Team
 * SPDX-License-Identifier: Apache-2.0
 * 
 * Contains: timer
 * 
 * Change Logs:
 * Date           Author            Notes
 * 2022-06-01     JasonHu           Init
 */

#include <nxos/syscall.h>
#include <nxos/timer.h>
#include <nxos/signal.h>
#include <nxos/utils.h>

NX_PRIVATE void TimerSignalHandler(NX_SignalInfo * signalInfo)
{
    // call timer handler
    if (signalInfo->extralInfo.timerHandler)
    {
        signalInfo->extralInfo.timerHandler(signalInfo->extralInfo.timerArg);
    }
}

NX_Solt NX_TimerCreate(NX_UArch milliseconds, void (*handler)(void *arg), void *arg, NX_U32 flags)
{
    NX_Solt solt = NX_SOLT_INVALID_VALUE;
    NX_Error err;
    NX_SignalAttr attr;

    /* update timer signal */
    NX_SignalGetAttr(NX_SIGNAL_TIMER, &attr);
    if (attr.handler != (void *)TimerSignalHandler)
    {
        NX_SignalInitAttr(&attr, TimerSignalHandler, NX_SIGNAL_FLAG_RESTART);
        NX_SignalSetAttr(NX_SIGNAL_TIMER, &attr);
    }

    /* call timer create syscall */
    NX_ErrorSet((err = NX_Syscall5(NX_API_TimerCreate, milliseconds, handler, arg, flags, &solt)));
    
    return solt;
}

NX_Error NX_TimerStart(NX_Solt solt)
{
    NX_Error err;

    NX_ErrorSet((err = NX_Syscall1(NX_API_TimerStart, solt)));
    return err;
}

NX_Error NX_TimerStop(NX_Solt solt)
{
    NX_Error err;

    NX_ErrorSet((err = NX_Syscall1(NX_API_TimerStop, solt)));
    return err;
}
